//
//  MemeViewController.m
//  reacticons
//
//  Created by Nong Nghia on 4/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MemeViewController.h"
#import "AppDelegate.h"
#import "Utilities.h"
#import "MemeCreatorViewController.h"
#import "ImageDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Globals.h"
#import "DatabaseConnection.h"
#import "Photo.h"
#import "LoadingView.h"

#define MAX_HIGHT 372.0
#define MAX_WIDTH 320.0


#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)


#define CAMERA_BTN_TAG 1
#define ADDPHOTO_BTN_TAG 2
#define SELECT_BTN 11
#define CANCEL_BTN 12
#define SHARE_BTN 13
#define COPY_BTN 14
#define DELETE_BTN 15

@interface MemeViewController ()

@end

@implementation MemeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationItem.title =@"Custom";

    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
    
    [Utilities showTabBar:nil];

    memeListItems = [[DatabaseConnection getCustomsPhotos] retain];
    DBLOG(@"%d",memeListItems.count);
    if (memeListItems) {
        if (memeListItems.count!=0) {
            [placeHolderLb setHidden:YES];
        }
    }
    
    if (myGridView) {
        [myGridView removeFromSuperview];
        [myGridView release];
        myGridView = nil;
    }
    
    myGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
    
    [myGridView setDelegate:self];
    [myGridView setDataSource:self];
    
    //    self.navigationItem.title=[NSString stringWithFormat:@"Favorites (%d)",imageListArray.count];
    
    [self.view insertSubview:myGridView atIndex:0];
    [myGridView reloadData];
    
    
}


-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad
{
    self.view.backgroundColor=[UIColor blackColor];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
     takePicture=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(btnWasClicked:)];
    
    [takePicture setTag:CAMERA_BTN_TAG];
//    [self.navigationItem setLeftBarButtonItem:takePicture];
    
    choosePhotos=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(btnWasClicked:)];

    [choosePhotos setTag:ADDPHOTO_BTN_TAG];
//    [self.navigationItem setRightBarButtonItem:choosePhotos];
    [self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:takePicture,choosePhotos, nil]];
    
    popUpBar = [[PopUpViewController alloc] init];
    [popUpBar.view setFrame:CGRectMake(0, 0, 72, 34)];
    [popUpBar.view setHidden:YES];
    [popUpBar setDelegate:self];
    [self.view addSubview:popUpBar.view];
    
    //popup label

    
    
    //
    [editBar setHidden:YES];
    [cancelNavBar setHidden:YES];
    
    UIBarButtonItem * editFavorites = [[UIBarButtonItem alloc] initWithTitle:@"Select"
                                                                       style:UIBarButtonItemStyleBordered
                                                                      target:self
                                                                      action:@selector(btnWasClicked:)];
    editFavorites.tag=SELECT_BTN;
    [self.navigationItem setRightBarButtonItem:editFavorites];
    isMultipleSelection = NO;
    [editFavorites release];


}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(IBAction)btnWasClicked:(id)sender{
    DBLOG(@"btnwasclicked - %d",[sender tag]);
    [popUpBar.view setHidden:YES];

    
    if ([sender tag]==CAMERA_BTN_TAG) {
        [self showImgPickerWithSourceType:UIImagePickerControllerSourceTypeCamera];

    }
    
    if ([sender tag]==ADDPHOTO_BTN_TAG) {
        [self showImgPickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    
    if ([sender tag]==SELECT_BTN) {
//        [popUpBar.view setHidden:YES];
        
        [copyBtn setTitle:@"Copy"];
        textlb.title=[NSString stringWithFormat:@"0 Photos Selected"];
        
        if (!listSelected) {
            listSelected=[[NSMutableArray alloc] init];
        }
        [Utilities hideTabBar:self.tabBarController];
        [myGridView setFrame:CGRectMake(0, 44, 320, APP_SCREEN_HEIGHT-43-44)];
        for (NSNumber *index in listSelected) {
            [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
        }
        [listSelected removeAllObjects];
        
        isMultipleSelection = YES;
        [myGridView setEnableMultipleSelection:YES];
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        [editBar setHidden:NO];
        [cancelNavBar setHidden:NO];
        [myGridView reloadData];
    }
    if ([sender tag]==CANCEL_BTN) {
        [Utilities showTabBar:self.tabBarController];
        
        [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
        
        for (NSNumber *index in listSelected) {
            [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
        }
        
        [listSelected removeAllObjects];
        isMultipleSelection = NO;
        [myGridView setEnableMultipleSelection:NO];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [editBar setHidden:YES];
        [cancelNavBar setHidden:YES];
        [myGridView reloadData];
    }
    
    if ([sender tag]==SHARE_BTN) {
        
        UIActionSheet * actionSheet=[[UIActionSheet alloc] initWithTitle:nil
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                  destructiveButtonTitle:nil
                                       otherButtonTitles:
                     @"Export To Phone Gallery",
                     @"Email",
                     nil];
        [actionSheet setTag:SHARE_BTN];
        [actionSheet showInView:editBar];
        [actionSheet release];
    }
    
    if ([sender tag]==COPY_BTN) {
        DBLOG(@"Copy and Messaging");
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSMutableArray *listImage=[[NSMutableArray alloc] init];
        for (NSNumber *index in listSelected) {
            [listImage addObject:[self imageAtIndex:[index intValue]]];
            [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
        }
        [listSelected removeAllObjects];
        pasteboard.images=[listImage retain];
        
        [Utilities showTabBar:self.tabBarController];
        
        [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
        isMultipleSelection = NO;
        [myGridView setEnableMultipleSelection:NO];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [editBar setHidden:YES];
        [cancelNavBar setHidden:YES];
        [myGridView reloadData];

    }
    if ([sender tag]==DELETE_BTN) {
      UIActionSheet *  actionSheet=[[UIActionSheet alloc] initWithTitle:nil
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                  destructiveButtonTitle:@"Delete"
                                       otherButtonTitles:nil];
        [actionSheet setTag:DELETE_BTN];
        [actionSheet showInView:editBar];
        [actionSheet release];
    }
   
    

    
    
}

#pragma mark - Pick Image & Take picture

-(void)showImgPickerWithSourceType:(UIImagePickerControllerSourceType)sourceType{
    if ([UIImagePickerController isSourceTypeAvailable:sourceType] == NO){
        return;
    }
    
    UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
    cameraUI.sourceType = sourceType;
    
    cameraUI.mediaTypes =
    [UIImagePickerController availableMediaTypesForSourceType:
     sourceType];
    
    cameraUI.allowsEditing = YES;
    
    cameraUI.delegate = self;
    
    
    [self presentModalViewController: cameraUI animated: YES];
}
- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")) {
        [self dismissViewControllerAnimated:YES
                                 completion:^{
                                     DBLOG(@"done");
                                 }];
    }
    else {
        [self dismissModalViewControllerAnimated: YES];
        
    }    [picker release];
}

// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
 didFinishPickingMediaWithInfo: (NSDictionary *) info {
    [[LoadingView sharedInstance] showLoadingView];
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;
    
    // Handle a still image capture
    
    //    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
    DBLOG(@"mediatype:%@",mediaType);
    if ([mediaType isEqualToString:@"public.image"]) {
        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];
        
        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }  
    }


    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")) {
        [self dismissViewControllerAnimated:YES 
                                 completion:^{
                                     DBLOG(@"done");
                                     [[LoadingView sharedInstance] stopLoadingView];
                                     [self showMemeCreator:imageToSave];

                                     
                                 }];
    }
    else {
//        [picker dismissModalViewControllerAnimated:YES];

        [picker dismissModalViewControllerAnimated:NO];

        [[LoadingView sharedInstance] stopLoadingView];
        [self showMemeCreator:imageToSave];


        
        
    }
    [picker release];
    
    
    
}
-(void)showMemeCreator:(UIImage*)img{
    MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
    [mcvc setImage:img];   
    [self presentModalViewController:mcvc animated:YES];
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    DBLOG(@"%@",viewController);
}



#pragma mark - utilities

#pragma mark - Grid View Data Source

- (NSInteger)numberOfCellsInGridView:(UIGridView *)gridView
{
    return [memeListItems count];
}

- (CGFloat)gridView:(UIGridView *)gridView heightForRowAtIndex:(NSInteger)rowIndex
{
    return 100;
}

- (NSInteger)gridView:(UIGridView *)gridView numberOfCellsPerRowInRow:(NSInteger)rowIndex
{
    return 3;
}

- (GridViewCell*)gridView:(UIGridView *)gridView cellAtIndex:(NSInteger)cellIndex
{
    UIGridViewCell_DownloadImage * cell = [[[UIGridViewCell_DownloadImage alloc] initWithFrame:CGRectZero] autorelease];
    
    if ([memeListItems count] == 0) {
        return nil;
    }
    Photo * photo = [memeListItems objectAtIndex:cellIndex];
    [cell setImageURLString:photo.photoImage];
    
    if (listSelected) {
        for (NSNumber *index in listSelected) {
            if ([index intValue]==cellIndex) {
                [cell setAccessoryType:UIGridViewCellAccessorySelected];
                [cell setIsSelected:YES];
                break;
            }
            else
            {
                [cell setAccessoryType:UIGridViewCellAccessoryNone];
                [cell setIsSelected:NO];
            }
        }
    }
    
    [cell setAccessoryType:UIGridViewCellAccessoryNone];

    [cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [cell.textLabel setHidden:YES];
    
    
    
    return cell;
}

#pragma mark - Grid View Delegate

- (void)gridView:(UIGridView *)gridView didSelectedCellAtIndex:(NSInteger)cellIndex
{
    if (!isMultipleSelection) {
        
        CGPoint offsetPoint = gridView.contentOffset;
        
        CGRect frame = [[myGridView cellAtIndex:cellIndex] frame];
        
        [popUpBar setSelectedFrame:CGRectMake(frame.origin.x - offsetPoint.x,
                                              frame.origin.y - offsetPoint.y,
                                              frame.size.width,
                                              frame.size.height)];
        
        
  
        [popUpBar setStatusOfFavoriteButtonAsActive:[DatabaseConnection isAddedToFavoriteWithPhotoID:[(Photo*)[memeListItems objectAtIndex:cellIndex] photoID]]];
  
        
        if (selectedCellIndex == cellIndex)
        {
            [popUpBar.view setHidden:!popUpBar.view.hidden];
        }
        else {
            [popUpBar.view setHidden:NO];
        }
        selectedCellIndex = cellIndex;
        [[UIPasteboard generalPasteboard] setImage:[self imageAtIndex:selectedCellIndex]];
        
   
    }
    else {
        BOOL isAdd=NO;
        for (int i=0;i<listSelected.count;i++) {
            if ([[listSelected objectAtIndex:i] intValue]==cellIndex) {
                [[myGridView cellAtIndex:cellIndex] setIsSelected:NO];
                [listSelected removeObjectAtIndex:i];
                isAdd=YES;
                break;
            }
        }
        if (!isAdd) {
            [listSelected addObject:[NSNumber numberWithInt:cellIndex]];
        }
        
        if ([listSelected count]>5) {
            [copyBtn setTitle:@"Copy"];
            [copyBtn setEnabled:NO];
        }
        else {
            [copyBtn setEnabled:YES];
            if (listSelected.count>0) {
                [copyBtn setTitle:[NSString stringWithFormat:@"Copy (%d)",listSelected.count]];
            }
            else {
                [copyBtn setTitle:@"Copy"];
            }
        }
        textlb.title=[NSString stringWithFormat:@"%d Photos Selected",listSelected.count];
        
    }
        
}

#pragma mark - POPUP Delegate

- (void)popUpBar:(PopUpViewController *)popUpController didSelectButton:(id)sender
{
    [self popupDidSelectBtnTag:[sender tag]];
    [popUpBar.view setHidden:YES];
}

-(void)popupDidSelectBtnTag:(int)tag{
    [[LoadingView sharedInstance] stopLoadingView];
    Photo *photo=(Photo*)[memeListItems objectAtIndex:selectedCellIndex];

    DBLOG(@"popupDidSelectBtnTag:%d",tag);

    ImageDetailViewController * detailView;
    switch (tag) {
        case 0:
            DBLOG(@"Share");
            [[UIPasteboard generalPasteboard] setImage:[self imageAtIndex:selectedCellIndex]];
            NSString *stringURL = @"sms:";
            NSURL *url = [NSURL URLWithString:stringURL];
            [[UIApplication sharedApplication] openURL:url]; 
            break;
            
        case 1:
            [popUpBar setStatusOfFavoriteButtonAsActive:[DatabaseConnection isAddedToFavoriteWithPhotoID:photo.photoID]];

            if ([DatabaseConnection isAddedToFavoriteWithPhotoID:[(Photo*)[memeListItems objectAtIndex:selectedCellIndex] photoID]]) {
                [DatabaseConnection deleteListItems:[NSMutableArray arrayWithObject:[photo itemObject]] fromEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
            }
            else {
//                [popUpBar.addToFavoriteButton setImage:[UIImage imageNamed:@"option_bar_btn.png"] forState:UIControlStateNormal];
                DBLOG(@"Add to Favorites....:%d",selectedCellIndex);
                
                Photo *photo=[memeListItems objectAtIndex:selectedCellIndex];
                
                [Utilities saveImage:[self imageAtIndex:selectedCellIndex]
                 toDocumentSubFolder:nil
                            withName:photo.photoName];
                
                [Utilities saveImage:[self imageAtIndex:selectedCellIndex]
                 toDocumentSubFolder:nil
                            withName:photo.photoThumbnail];
                
                NSString *filePath=[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:photo.photoName];
                NSURL *fileURL =[NSURL fileURLWithPath:filePath];
                
                [photo setPhotoImage:[fileURL absoluteString]];
                
                [photo setPhotoThumbnail:[fileURL absoluteString]];
                [photo setPhotoCreatedDate:[Utilities uniqueStringWithPrefix:@""]];
                [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[photo itemObject]] toEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
            }            
            
            break;
            
        case 2:
            DBLOG(@"View detail");
            detailView = [[ImageDetailViewController alloc] init];
            [detailView setItemList:memeListItems];
            [detailView setItemIndex:selectedCellIndex];
            [detailView setItemType:@"meme"];
            self.navigationItem.title=@"Back";
            [self.navigationController pushViewController:detailView animated:YES];
            
            [detailView release];
            
            break;
            
        default:
            break;
    }
    if (tag==3) {
        MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
        [mcvc setImage:[self imageAtIndex:selectedCellIndex]];
        [self presentModalViewController:mcvc animated:YES];
    }
}
- (UIImage *)imageAtIndex:(NSUInteger)index {
    
    DBLOG(@"ImageListViewController - imageAtIndex:%d",index);
    Photo *photo = [memeListItems objectAtIndex:index];
    
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *targetPath=[documentPath stringByAppendingPathComponent:@"Meme"];
    NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];
    
    if ([fm fileExistsAtPath:targetPath]) {
        return [UIImage imageWithContentsOfFile:[targetPath stringByAppendingPathComponent:[[photo photoImage] lastPathComponent]]];
    }
    else {
        return nil;
    }
}



#pragma mark - UIActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([actionSheet tag]==SHARE_BTN) {
        if (buttonIndex==0) {
            
            
            [Utilities showTabBar:self.tabBarController];
            for (NSNumber *index in listSelected) {
                UIImageWriteToSavedPhotosAlbum([self imageAtIndex:[index intValue]], nil,nil,nil);
                [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
            }
            
            [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];
            
            memeListItems = [[DatabaseConnection getCustomsPhotos] retain];
            self.navigationItem.title=@"Custom";
            [myGridView reloadData];
            return;
        }
        if (buttonIndex==1) {
            
            [self sendMail];
            
            
            return;
        }
    }
    
    if ([actionSheet tag]==DELETE_BTN) {
        if (buttonIndex==0) {
            
            DBLOG(@"list:%@",listSelected);
            [Utilities showTabBar:self.tabBarController];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];
//            NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//            NSString *favoritePath=[documentPath stringByAppendingPathComponent:@"Meme"];
//            
//            NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];
            NSMutableArray *itemArray=[[NSMutableArray alloc] init];
            
            for (NSNumber *index in listSelected) {
                [itemArray addObject:[(Photo*)[memeListItems objectAtIndex:[index intValue]] itemObject]];
            }
            [listSelected removeAllObjects];
            [DatabaseConnection deleteListItems:itemArray fromEntity:@"ManagedCustomPhoto" withPrimaryKey:@"photoID"];
            [itemArray release];
            memeListItems = [[DatabaseConnection getCustomsPhotos] retain];
            self.navigationItem.title=@"Custom";
            [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            [myGridView reloadData];
            if (memeListItems.count==0) {
                [placeHolderLb setHidden:NO];
            }
            [myGridView scrollsToTop];
            
            return;
        }
        
    }
}

#pragma mark - MFMailComposeViewController Delegate

-(void)sendMail{
    
    if ([MFMailComposeViewController canSendMail]) {
        
        // Fill out the email body text
        //Create a string with HTML formatting for the email body
        NSString *iTunesLink = @"itms-apps://itunes.com/apps/reacticons"; // replate it with yours
        NSString *emailBody =
        [NSString stringWithFormat:@"\n<p>Sent from Reacticons! ...an gallery app of all reaction images.</br> <a href = '%@'>Download</a> it now!</p>", iTunesLink];
       MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;
//        [emailDialog setSubject:@"My Inline Image Document"];
        [emailDialog setMessageBody:emailBody isHTML:YES];
        
        //Pick an image to insert
        //This example would come from the main bundle, but your source can be elsewhere
        for (NSNumber *index in listSelected) {
            
            UIImage *emailImage = [self imageAtIndex:[index intValue]];
            
            NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
            
            [emailDialog addAttachmentData:imageData mimeType:@"png" fileName:[[(Photo*)[memeListItems objectAtIndex:[index intValue]] photoImage] lastPathComponent]];
            
        }
        
        
        [self presentModalViewController:emailDialog animated:YES];
        [emailDialog release];
        
        
    }
    else {
        
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Cannot Send Via Mail" message:@"Please setup your mail before share via Email" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    
    [Utilities showTabBar:self.tabBarController];
    for (NSNumber *index in listSelected) {
        [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
    }
    [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [editBar setHidden:YES];
    [cancelNavBar setHidden:YES];
    
    memeListItems = [[DatabaseConnection getCustomsPhotos] retain];
    self.navigationItem.title=@"Custom";
    
    isMultipleSelection = NO;
    [myGridView setEnableMultipleSelection:NO];
    [myGridView reloadData];
    
}

-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    
    [self dismissModalViewControllerAnimated:YES];

}



@end
